<template>
  <div class="center-panel">
    <!-- 数据看板 -->
    <div class="metrics">
      <metric-card
        v-for="(item, index) in metrics"
        :key="index"
        :title="item.title"
        :value="item.value"
        :trend="item.trend"
        :loading="loading"
        class="metric-item"
      />
    </div>

    <!-- 可视化图表 -->
    <div
      v-loading="loading"
      ref="chart"
      class="chart-item"
      style="height: 500px;"
    ></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import { getDashboardStats } from '@/api/suggestion/suggestion';
import MetricCard from './MetricCard.vue';

export default {
  components: { MetricCard },
  data() {
    return {
      loading: true,
      metrics: [
        { title: '年度建议数', value: 0, trend: 0 },
        { title: '本月提交量', value: 0, trend: 0 },
        { title: '今日建议数', value: 0, trend: 0 },
        { title: '处理成功率', value: 0, unit: '%' },
        { title: '活跃用户数', value: 0, trend: 0 },
        { title: '未处理建议', value: 0, trend: 0 },
      ],
      chart: null,
    };
  },
  mounted() {
    this.fetchData();
    this.setAutoRefresh();
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    clearInterval(this.timer);
    if (this.chart) this.chart.dispose();
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    async fetchData() {
      try {
        this.loading = true;
        const res = await getDashboardStats();

        console.log('完整响应数据:', res);

        if (Array.isArray(res) && res.length > 0) {
          const firstItem = res[0];
          if (firstItem.code === 200) {
            if (firstItem.rows && Array.isArray(firstItem.rows) && firstItem.rows.length > 0) {
              const dashboardStats = firstItem.rows[0];

              // 更新指标数据
              this.metrics[0].value = dashboardStats.annualSuggestions || 0;
              this.metrics[1].value = dashboardStats.monthlySuggestions || 0;
              this.metrics[2].value = dashboardStats.dailySuggestions || 0;
              this.metrics[3].value = dashboardStats.successRate || 0;
              this.metrics[4].value = dashboardStats.activeUsers || 0;
              this.metrics[5].value = dashboardStats.pendingSuggestions || 0;

              // 更新趋势数据
              this.metrics[0].trend = dashboardStats.annualTrend || 0;
              this.metrics[1].trend = dashboardStats.monthlyTrend || 0;
              this.metrics[2].trend = dashboardStats.dailyTrend || 0;
              this.metrics[4].trend = dashboardStats.activeTrend || 0;

              // 更新雷达图数据
              this.updateRadarChart([
                { name: '年度建议数', value: this.metrics[0].value },
                { name: '本月提交量', value: this.metrics[1].value },
                { name: '今日建议数', value: this.metrics[2].value },
                { name: '未处理建议', value: this.metrics[5].value },
                { name: '活跃用户数', value: this.metrics[4].value },
                { name: '处理成功率', value: this.metrics[3].value },
              ]);

              console.log('指标数据更新成功:', dashboardStats);
            }
          }
        }
      } catch (error) {
        console.error('数据获取失败:', error);
        this.$message.error('看板数据加载失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },

    updateRadarChart(data) {
      if (!this.chart) {
        this.chart = echarts.init(this.$refs.chart);
      }

      // 生成雷达图指标配置
      const indicators = data.map(item => ({
        name: item.name,
        max: Math.max(Math.ceil(item.value * 1.2), 10) // 动态计算最大值
      }));

      const option = {
        title: {
          text: '建议分布雷达图',
          left: 'center',
          textStyle: {
            color: '#333',
            fontSize: 16
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            return `${params.name}<br/>数值: ${params.value}${params.name === '处理成功率' ? '%' : ''}`;
          }
        },
        radar: {
          indicator: indicators,
          shape: 'polygon',
          splitNumber: 5,
          center: ['50%', '52%'],
          radius: '65%',
          axisName: {
            color: '#666',
            fontSize: 12,
            formatter: (name, indicator) => {
              return `{a|${name}}\n{b|${indicator.max}}`;
            },
            rich: {
              a: {
                fontSize: 12,
                color: '#666'
              },
              b: {
                fontSize: 10,
                color: '#999',
                padding: [5, 0, 0, 0]
              }
            }
          },
          splitArea: {
            areaStyle: {
              color: ['rgba(114, 172, 209, 0.2)',
                'rgba(114, 172, 209, 0.4)',
                'rgba(114, 172, 209, 0.6)',
                'rgba(114, 172, 209, 0.8)',
                'rgba(114, 172, 209, 1)']
            }
          },
          axisLine: {
            lineStyle: {
              color: 'rgba(100, 100, 100, 0.5)'
            }
          }
        },
        series: [{
          type: 'radar',
          data: [{
            value: data.map(item => item.value),
            name: '指标分布',
            label: {
              show: true,
              position: 'top',
              distance: 5,
              color: '#409EFF',
              fontSize: 12,
              formatter: (params) => {
                return params.value + (params.name === '处理成功率' ? '%' : '');
              }
            },
            areaStyle: {
              color: 'rgba(64, 158, 255, 0.4)'
            },
            lineStyle: {
              color: '#409EFF',
              width: 2
            },
            itemStyle: {
              color: '#409EFF',
              borderWidth: 2
            }
          }]
        }]
      };

      this.chart.setOption(option);
    },

    setAutoRefresh() {
      this.timer = setInterval(() => {
        this.fetchData();
      }, 300000);
    },

    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    }
  }
};
</script>

<style scoped>
.center-panel {
  display: flex;
  flex-direction: column;
  gap: 24px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
  min-height: 100vh;
}

.metrics {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(2, 1fr);
  gap: 16px;
}

.metric-item {
  width: 100%;
  aspect-ratio: 1 / 1;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 15px;
}

.chart-item {
  width: 100%;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .metrics {
    grid-template-columns: repeat(2, 1fr);
  }

  .chart-item {
    height: 400px;
  }
}
</style>
